import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { useSongAPI } from "@/services/song";
import { useUserStore } from "@/stores/user";

export const usePlayerStore = defineStore(
  "player",
  () => {
    const songAPI = useSongAPI();
    const userStore = useUserStore();
    const currentSong = ref<any>(null);
    const isPlaying = ref(false);
    const currentTime = ref(0);
    const duration = ref(0);
    const currentLyricIndex = ref(-1); // 添加当前歌词索引
    const queue = ref<any[]>([]);
    const currentIndex = ref(-1);

    const playSong = async (song: any, songList?: any[]) => {
      resetPlayer();
      currentSong.value = song;
      console.log(currentSong.value);
      isPlaying.value = true;

      // 处理播放队列
      if (songList) {
        queue.value = [...songList];
        currentIndex.value = queue.value.findIndex((s) => s.id === song.id);
      } else if (!queue.value.some((s) => s.id === song.id)) {
        queue.value.push(song);
        currentIndex.value = queue.value.length - 1;
      } else {
        currentIndex.value = queue.value.findIndex((s) => s.id === song.id);
      }

      // 添加播放历史记录
      if (userStore.isLogin && song.id) {
        try {
          await songAPI.addPlayRecord(userStore.uid, song.id);
        } catch (error) {
          console.error("添加播放历史记录失败:", error);
        }
      }
    };

    const togglePlay = () => {
      isPlaying.value = !isPlaying.value;
    };

    const parseLyric = (lyric: string) => {
      if (!lyric) return [];
      const lines = lyric.split("\n");
      const timeExp = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;

      return lines
        .map((line) => {
          const matches = timeExp.exec(line);
          if (!matches) return null;

          const minutes = parseInt(matches[1]);
          const seconds = parseInt(matches[2]);
          const milliseconds = parseInt(matches[3]);
          const time = minutes * 60 + seconds + milliseconds / 1000;
          const text = line.replace(timeExp, "").trim();

          return { time, text };
        })
        .filter((item) => item !== null);
    };

    const updateCurrentLyric = (time: number) => {
      if (!currentSong.value?.lyric) return;
      const lyrics = parseLyric(currentSong.value.lyric);
      const index = lyrics.findIndex((lyric: any) => lyric.time > time) - 1;
      currentLyricIndex.value = index;
    };

    // 在 updateTime 方法中添加歌词更新
    const updateTime = (time: number) => {
      currentTime.value = time;
      updateCurrentLyric(time);
    };

    const updateDuration = (total: number) => {
      duration.value = total;
    };

    const formatTime = (time: number) => {
      const minutes = Math.floor(time / 60);
      const seconds = Math.floor(time % 60);
      return `${minutes.toString().padStart(2, "0")}:${seconds
        .toString()
        .padStart(2, "0")}`;
    };

    const setPlaying = (status: boolean) => {
      isPlaying.value = status;
    };

    const resetPlayer = () => {
      currentTime.value = 0;
      duration.value = 0;
      isPlaying.value = false;
    };

    const setCurrentSong = (song: any) => {
      currentSong.value = song;
      // 如果在队列中存在这首歌，也更新队列中的收藏状态
      if (currentIndex.value !== -1) {
        queue.value[currentIndex.value] = { ...song };
      }
    };

    const addToQueue = (song: any) => {
      queue.value.push(song);
      if (currentIndex.value === -1) {
        currentIndex.value = 0;
        currentSong.value = song; // 直接设置 currentSong
      }
    };

    const playFromQueue = (index: number) => {
      if (index >= 0 && index < queue.value.length) {
        currentIndex.value = index;
        currentSong.value = queue.value[index]; // 直接设置 currentSong
        setPlaying(true);
      }
    };

    const playNext = () => {
      if (queue.value.length > 0) {
        const nextIndex = (currentIndex.value + 1) % queue.value.length;
        playFromQueue(nextIndex);
      }
    };

    const playPrevious = () => {
      if (queue.value.length > 0) {
        const prevIndex =
          (currentIndex.value - 1 + queue.value.length) % queue.value.length;
        playFromQueue(prevIndex);
      }
    };

    const clearQueue = () => {
      queue.value = [];
      currentIndex.value = -1;
    };

    return {
      currentSong,
      isPlaying,
      currentTime,
      duration,
      playSong,
      togglePlay,
      updateTime,
      updateDuration,
      formatTime,
      setPlaying,
      resetPlayer,
      currentLyricIndex,
      parseLyric,
      queue,
      currentIndex,
      addToQueue,
      playFromQueue,
      playNext,
      playPrevious,
      clearQueue,
      setCurrentSong,
    };
  },
  {
    persist: true,
  }
);
